package com.ciwong.epaper.modules.reciteWords.ui;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.reciteWords.adapter.PopWindowRecyclerViewAdapter;
import com.ciwong.epaper.modules.reciteWords.adapter.VocabularyRecyclerViewAdapter;
import com.ciwong.epaper.modules.reciteWords.bean.JiaoCaiBean;
import com.ciwong.epaper.modules.reciteWords.bean.JiaoCaiDetailBean;
import com.ciwong.epaper.modules.reciteWords.bean.LearnBookStatus;
import com.ciwong.epaper.modules.reciteWords.bean.MakePlanSuccessBean;
import com.ciwong.epaper.modules.reciteWords.bean.PeriodVersionBean;
import com.ciwong.epaper.modules.reciteWords.bean.SelectVocabularyBean;
import com.ciwong.epaper.modules.reciteWords.bean.SelectedJiaoCaiVersionBean;
import com.ciwong.epaper.modules.reciteWords.bean.ShowJiaoCaiInfo;
import com.ciwong.epaper.modules.reciteWords.dao.WordDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by keepon on 2018/9/13.
 */
public class SelectVocabularyActivity extends BaseActivity {

	private RecyclerView                  mRecyclerView;
	private RecyclerView                  mPopRecyclerView;
	//没有数据时的展示
	private LinearLayout                  llNoData;
	//没有网络时的展示
	private LinearLayout                  llNoNet;
	//没有网络时的重试按钮
	private Button                        tv_retry;
	private VocabularyRecyclerViewAdapter mVocabularyRecyclerViewAdapter;
	private PopWindowRecyclerViewAdapter  mPopWindowRecyclerViewAdapter;
	List<SelectVocabularyBean> mSelectVocabularyBeanList = new ArrayList<>();
	private View              mShadeView;
	private SelectedJiaoCaiVersionBean mSelectedJiaoCaiVersionBean;
	private PopupWindow mWindow;
	private   int mBookId;
	private   int mJumpFrom ;
	private List<LearnBookStatus> mLearnBookStatusList;

	@Override
	protected int setView() {
		return R.layout.activity_select_vocabulary;
	}

	@Override
	protected void findViews() {
		mRecyclerView = findViewById(R.id.recycler_view);
		mShadeView = findViewById(R.id.shade_view);

		llNoData = findViewById(R.id.ll_no_data);
		llNoNet = findViewById(R.id.ll_no_net);
		tv_retry = findViewById(R.id.btn_retry);
		initPopWindowView();
	}

	@Override
	protected void initEvent() {
		tv_retry.setOnClickListener(new View.OnClickListener() {//重试按钮（网络问题）
			@Override
			public void onClick(View v) {
				if (NetworkUtils.isOnline()) {
						getReciteWordsFromNet();
				} else {
					ToastUtil.INSTANCE.toastInCenter(SelectVocabularyActivity.this, getResources().getString(R.string.connect_disable5), Toast.LENGTH_LONG);
				}

			}
		});

	}

	@Override
	protected void init() {

		if(getIntent()!=null){
			mBookId =getIntent().getIntExtra(IntentFlag.INTENT_FLAG_BOOKID,0);
			mJumpFrom =getIntent().getIntExtra(IntentFlag.INTENT_FLAG_JUMP_FROM,0);
		}
		EventBus.getDefault().register(this);
		setTitleText("选择词汇");
		setRightBtnTextAndRightDrawable("全部", R.mipmap.icon_pull_down);

		ArrayList<ShowJiaoCaiInfo> showJiaoCaiInfosList     = new ArrayList<>();
		mRecyclerView.setLayoutManager(new LinearLayoutManager(SelectVocabularyActivity.this));
		mVocabularyRecyclerViewAdapter = new VocabularyRecyclerViewAdapter(SelectVocabularyActivity.this, showJiaoCaiInfosList);
		mRecyclerView.setAdapter(mVocabularyRecyclerViewAdapter);


		mPopRecyclerView.setLayoutManager(new LinearLayoutManager(SelectVocabularyActivity.this));
		mPopWindowRecyclerViewAdapter = new PopWindowRecyclerViewAdapter(SelectVocabularyActivity.this, mSelectVocabularyBeanList);
		mPopRecyclerView.setAdapter(mPopWindowRecyclerViewAdapter);
		mPopWindowRecyclerViewAdapter.setOnSelectClickListener(new PopWindowRecyclerViewAdapter.OnSelectClickListener() {
			@Override
			public void onItemSelected(int positon, JiaoCaiBean jiaoCaiBean, String periodName) {
				if (TextUtils.isEmpty(periodName)) {
					return;
				}

				//选中的是全部
				if ("全部".equals(periodName)) {
					for (SelectVocabularyBean vocabularyBean : mSelectVocabularyBeanList) {
						if (vocabularyBean.getChildren() != null) {
							for (JiaoCaiBean caiBean : vocabularyBean.getChildren()) {
								caiBean.setSelected(false);
							}
						}
					}
				} else {
					for (SelectVocabularyBean vocabularyBean : mSelectVocabularyBeanList) {
						//同学段其他设置不选中
						if (periodName.equals(vocabularyBean.getPeriodName())) {
							if (vocabularyBean.getChildren() != null) {
								for (JiaoCaiBean caiBean : vocabularyBean.getChildren()) {
									if (jiaoCaiBean.getVersionName().equals(caiBean.getVersionName())) {
										caiBean.setSelected(true);
									} else {
										caiBean.setSelected(false);
									}
								}
							}
						} else {
							//不同学段所有设置不选中
							if (vocabularyBean.getChildren() != null) {
								if (vocabularyBean.getChildren() != null) {
									for (JiaoCaiBean caiBean : vocabularyBean.getChildren()) {
										caiBean.setSelected(false);
									}
								}
							}
						}
					}
				}

				mPopWindowRecyclerViewAdapter.updateDatas(mSelectVocabularyBeanList, periodName);
				filterShowingJiaoCaiInfos(new PeriodVersionBean(periodName, jiaoCaiBean.getVersionName()), mSelectVocabularyBeanList,mLearnBookStatusList);
			}
		});

		setRightBtnListener(new ViewOnClickListener() {
			@Override
			public void avertRepeatOnClick(View v) {
				showPopupWindow(titleBar);
			}
		});




	}


	@Override
	protected void loadData() {
		loadLocalData();
	}

	private void getReciteWordsFromNet() {
		WordDao.getInstance().getRecitewordsVersion(new BaseExtCallBack(SelectVocabularyActivity.this) {
			@Override
			public void failed(int errorCode, Object data) {
				super.failed(errorCode,data);
				changeShowIsHaveData(false);
				hideCricleProgress();
			}

			@Override
			public void failed(Object data) {
				super.failed(data);
				changeShowIsHaveData(false);
				hideCricleProgress();
			}

			@Override
			public void success(Object data) {
				List<SelectVocabularyBean> selectVocabularyBeanList = (List<SelectVocabularyBean>) data;
				mSelectVocabularyBeanList=selectVocabularyBeanList;
				long userId = EApplication.getInstance().getUserInfoBase().getUserId();
				WordDao.getInstance().getBookLearning((int) userId, new BaseCallBack() {
					@Override
					public void failed(int errorCode, Object data) {
						hideCricleProgress();
						changeShowIsHaveData(false);
					}

					@Override
					public void failed(Object data) {
						hideCricleProgress();
						changeShowIsHaveData(false);
					}

					@Override
					public void success(Object data) {
						hideCricleProgress();
						if(data !=null ){
							mLearnBookStatusList = (List<LearnBookStatus>) data;
							changeShowIsHaveData(true);
							//本地已经有选中教材
							if (mSelectedJiaoCaiVersionBean != null) {
								PeriodVersionBean periodVersionBean = mSelectedJiaoCaiVersionBean.getPeriodVersionBean();
								filterShowingJiaoCaiInfos(periodVersionBean, mSelectVocabularyBeanList, mLearnBookStatusList);

								setSelectedPersiodVersion(periodVersionBean);
							} else {
								//默认显示全部
								filterShowingJiaoCaiInfos(new PeriodVersionBean("全部", "全部"), mSelectVocabularyBeanList, mLearnBookStatusList);
							}
							mPopWindowRecyclerViewAdapter.updateDatas(mSelectVocabularyBeanList);
						}else{
							changeShowIsHaveData(false);
						}

					}
				});



			}
		});
	}

	//把选中的教材版本同步到最新的数据中
	private void setSelectedPersiodVersion(PeriodVersionBean periodVersionBean) {
		if(mSelectVocabularyBeanList!=null&&periodVersionBean!=null){
			for (SelectVocabularyBean selectVocabularyBean : mSelectVocabularyBeanList) {
				if(selectVocabularyBean.getPeriodName().equals(periodVersionBean.getPeriodName())){
					List<JiaoCaiBean> children = selectVocabularyBean.getChildren();
					if(children!=null){
						for (JiaoCaiBean jiaoCaiBean : children) {
							if(jiaoCaiBean.getVersionName().equals(periodVersionBean.getVersionName())){
								jiaoCaiBean.setSelected(true);
							}
						}
					}
				}
			}
		}

	}

	private void filterShowingJiaoCaiInfos(PeriodVersionBean periodVersionBean, List<SelectVocabularyBean> selectVocabularyBeanList,List<LearnBookStatus> learnBookStatusList) {
		if (selectVocabularyBeanList == null || periodVersionBean == null) {
			return;
		}
		List<ShowJiaoCaiInfo> showJiaoCaiInfosList= filterShowingJiaoBySelectedVersion(selectVocabularyBeanList, periodVersionBean.getPeriodName(), periodVersionBean.getVersionName(),learnBookStatusList);

		if (mSelectedJiaoCaiVersionBean == null) {
			mSelectedJiaoCaiVersionBean = new SelectedJiaoCaiVersionBean();
		}
		mSelectedJiaoCaiVersionBean.setShowJiaoCaiInfoList(showJiaoCaiInfosList);
		mSelectedJiaoCaiVersionBean.setPeriodVersionBean(periodVersionBean);
		SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_SELECT_JIAOCAI_VERSIONS, mSelectedJiaoCaiVersionBean);
	}

	private List<ShowJiaoCaiInfo> filterShowingJiaoBySelectedVersion(List<SelectVocabularyBean> selectVocabularyBeanList, String periodName, String selectedVersionName,List<LearnBookStatus> learnBookStatusList) {
		List<ShowJiaoCaiInfo> netShowJiaoCaiInfoLists = new ArrayList();
		for (SelectVocabularyBean selectVocabularyBean : selectVocabularyBeanList) {
			ShowJiaoCaiInfo showJiaoCaiInfo = new ShowJiaoCaiInfo();

			List<JiaoCaiDetailBean> jiaoCaiDetailBeanList = new ArrayList<>();
			//设置学段名字
			showJiaoCaiInfo.setPeriodName(selectVocabularyBean.getPeriodName());
			showJiaoCaiInfo.setPeriodId(selectVocabularyBean.getPeriodId());
			showJiaoCaiInfo.setJiaoCaiDetailBeanList(jiaoCaiDetailBeanList);
			showJiaoCaiInfo.setSelectedVersionName(selectedVersionName);

			if ("全部".equals(selectedVersionName)) {
				List<JiaoCaiBean> children = selectVocabularyBean.getChildren();
				if (children != null) {
					for (JiaoCaiBean jiaoCaiBean : children) {
						if (jiaoCaiBean != null) {
							jiaoCaiDetailBeanList =setLearningBookStatus(jiaoCaiDetailBeanList,learnBookStatusList, jiaoCaiBean);
						}
					}
				}
				netShowJiaoCaiInfoLists.add(showJiaoCaiInfo);
			} else {
				List<JiaoCaiBean> children = selectVocabularyBean.getChildren();
				if (periodName.equals(selectVocabularyBean.getPeriodName())) {
					if (children != null) {
						for (JiaoCaiBean jiaoCaiBean : children) {
							if (jiaoCaiBean != null && selectedVersionName.equals(jiaoCaiBean.getVersionName())) {
								jiaoCaiDetailBeanList =setLearningBookStatus(jiaoCaiDetailBeanList,learnBookStatusList, jiaoCaiBean);
							}
						}
					}
					netShowJiaoCaiInfoLists.add(showJiaoCaiInfo);
				}
			}

		}
		setLearningBook(netShowJiaoCaiInfoLists);
		mVocabularyRecyclerViewAdapter.updateDatas(netShowJiaoCaiInfoLists);
		setRighText(selectedVersionName);

		return netShowJiaoCaiInfoLists;
	}

	//把已经创建计划的书籍的状态同步
	private List<JiaoCaiDetailBean> setLearningBookStatus( List<JiaoCaiDetailBean> jiaoCaiDetailBeanList,List<LearnBookStatus> learnBookStatusList,JiaoCaiBean jiaoCaiBean ) {
		try {
			List<JiaoCaiDetailBean> jiaoCaiBeanChildren = jiaoCaiBean.getChildren();
			if(jiaoCaiBeanChildren!=null){
				for (JiaoCaiDetailBean jiaoCaiDetailBean : jiaoCaiBeanChildren) {
					if(learnBookStatusList!=null){
						for (LearnBookStatus learnBookStatus : learnBookStatusList) {
							if(jiaoCaiDetailBean.getVersionId()==learnBookStatus.getBookId()){
								jiaoCaiDetailBean.setStatus(learnBookStatus.getStatus());
								jiaoCaiDetailBean.setLearnCount(learnBookStatus.getLearnCount());
							}
						}
					}
					jiaoCaiDetailBeanList.add(jiaoCaiDetailBean);
				}
			}
		}catch (Exception e){

		}

		return jiaoCaiDetailBeanList;
	}

	private void setRighText(String text) {
		setRightBtnText(text);
		mPopWindowRecyclerViewAdapter.setIsSelectedAll(text);
	}

	private void initPopWindowView() {
		mPopRecyclerView = (RecyclerView) LayoutInflater.from(this).inflate(R.layout.layout_pop_window_select_jiaocai, null);
	}

	//控件下方弹出窗口
	private void showPopupWindow(View view) {
		try {
			if(mWindow==null){
				mWindow = new PopupWindow(mPopRecyclerView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);

				mWindow.setTouchable(true);
				mWindow.setTouchInterceptor(new View.OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return false;
						//这里如果返回true的话，touch事件将被拦截
						//拦截后 PoppWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
					}
				});
				//（注意一下！！）如果不设置popupWindow的背景，无论是点击外部区域还是Back键都无法弹框
				mWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
				mWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
					@Override
					public void onDismiss() {
						mShadeView.setVisibility(View.GONE);
						titleBar.setRightBtnRightDrawable(R.mipmap.icon_pull_down);
					}
				});
				//设置popwindow的显示和消失动画
				mWindow.setAnimationStyle(R.style.toppopwindow_anim_style);
			}

			mWindow.showAsDropDown(view);
			mShadeView.setVisibility(View.VISIBLE);
			titleBar.setRightBtnRightDrawable(R.mipmap.icon_pull_up);
		}catch (Exception e){

		}

	}


	public void loadLocalData() {
		showCricleProgress();
		SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_SELECT_JIAOCAI_VERSIONS, new BaseCallBack() {
			@Override
			public void success(Object data) {
				hideCricleProgress();
				SelectedJiaoCaiVersionBean selectedJiaoCaiVersionBean = (SelectedJiaoCaiVersionBean) data;
				List<ShowJiaoCaiInfo> showJiaoCaiInfos = selectedJiaoCaiVersionBean.getShowJiaoCaiInfoList();
				setLearningBook(showJiaoCaiInfos);
				mVocabularyRecyclerViewAdapter.updateDatas(showJiaoCaiInfos);
				mSelectedJiaoCaiVersionBean = selectedJiaoCaiVersionBean;
				getReciteWordsFromNet();
			}

			@Override
			public void failed(int errorCode, Object data) {
				getReciteWordsFromNet();
			}

			@Override
			public void failed(Object data) {
				getReciteWordsFromNet();
			}
		});
	}

	private void setLearningBook(List<ShowJiaoCaiInfo> showJiaoCaiInfos) {
		if(mJumpFrom== IntentValue.JumpSelectVocabularyType.FROM_CHANGE_PLAN&&mBookId!=0&&showJiaoCaiInfos!=null){
			for (ShowJiaoCaiInfo showJiaoCaiInfo : showJiaoCaiInfos) {
				List<JiaoCaiDetailBean> jiaoCaiDetailBeanList = showJiaoCaiInfo.getJiaoCaiDetailBeanList();
				if(jiaoCaiDetailBeanList!=null){
					for (JiaoCaiDetailBean jiaoCaiDetailBean : jiaoCaiDetailBeanList) {
						if(mBookId==jiaoCaiDetailBean.getVersionId()){
							jiaoCaiDetailBean.setSelected(true);
						}else{
							jiaoCaiDetailBean.setSelected(false);
						}
					}
				}
			}
		}
	}

	private void changeShowIsHaveData(boolean haveDate) {
		if (haveDate) {
			mRecyclerView.setVisibility(View.VISIBLE);
			llNoData.setVisibility(View.GONE);
			llNoNet.setVisibility(View.GONE);
		} else {
			mRecyclerView.setVisibility(View.GONE);
			if(NetworkUtils.isOnline()){
				llNoData.setVisibility(View.VISIBLE);
				llNoNet.setVisibility(View.GONE);
			}else{
				llNoData.setVisibility(View.GONE);
				llNoNet.setVisibility(View.VISIBLE);
			}

		}
	}
	public void onEventMainThread(MakePlanSuccessBean successBean) {
		finish();
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
}
